<template>
  <div class="workshop-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>车间管理</span>
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增车间</el-button>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="车间编码">
          <el-input
            v-model="searchForm.workshop_code"
            placeholder="请输入车间编码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="车间名称">
          <el-input
            v-model="searchForm.workshop_name"
            placeholder="请输入车间名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="车间类型">
          <el-select
            v-model="searchForm.workshop_type"
            placeholder="请选择车间类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(label, value) in workshopTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 车间列表 -->
      <el-table
        v-loading="workshopStore.loading"
        :data="workshopStore.paginatedWorkshops"
        style="width: 100%"
        border
      >
        <el-table-column prop="workshop_code" label="车间编码" width="120" />
        <el-table-column prop="workshop_name" label="车间名称" width="180" />
        <el-table-column prop="warehouse_name" label="所属仓库" width="150" />
        <el-table-column prop="workshop_type" label="车间类型" width="120">
          <template #default="scope">
            {{ getWorkshopTypeLabel(scope.row.workshop_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="production_capacity" label="生产能力" width="120" />
        <el-table-column prop="manager_name" label="负责人" width="100" />
        <el-table-column prop="phone_number" label="联系电话" width="150" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_active"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
              :disabled="!hasPermission('workshop:status')"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              link
              @click="handleEdit(scope.row)"
              :disabled="!hasPermission('workshop:edit')"
            >
              编辑
            </el-button>
            <el-button
              link
              danger
              @click="handleDelete(scope.row)"
              :disabled="!hasPermission('workshop:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="workshopStore.currentPage"
          v-model:page-size="workshopStore.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="workshopStore.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑车间对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="workshopFormRef"
        :model="workshopForm"
        :rules="formRules"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="车间编码" prop="workshop_code">
          <el-input
            v-model="workshopForm.workshop_code"
            placeholder="请输入车间编码"
            clearable
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="车间名称" prop="workshop_name">
          <el-input
            v-model="workshopForm.workshop_name"
            placeholder="请输入车间名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="所属仓库" prop="warehouse_id">
          <el-select
            v-model="workshopForm.warehouse_id"
            placeholder="请选择所属仓库"
            clearable
          >
            <!-- 实际项目中应从仓库管理获取数据 -->
            <el-option label="成品仓库" :value="1" />
            <el-option label="原料仓库" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="车间类型" prop="workshop_type">
          <el-select
            v-model="workshopForm.workshop_type"
            placeholder="请选择车间类型"
            clearable
          >
            <el-option
              v-for="(label, value) in workshopTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产能力" prop="production_capacity">
          <el-input-number
            v-model="workshopForm.production_capacity"
            placeholder="请输入生产能力"
            :min="0"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="manager_name">
          <el-input
            v-model="workshopForm.manager_name"
            placeholder="请输入负责人姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone_number">
          <el-input
            v-model="workshopForm.phone_number"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="workshopForm.address"
            placeholder="请输入车间地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="workshopForm.description"
            placeholder="请输入车间描述"
            type="textarea"
            rows="3"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseWorkShopStore } from '@/stores/base/BaseWorkshopStore';
import type { WorkshopQueryParams, WorkshopCreateParams, WorkshopUpdateParams, WorkshopStatusParams } from '@/types/base/BaseWorkshop';

// 车间类型选项
const workshopTypeOptions: Record<number, string> = {
  1: '生产车间',
  2: '装配车间',
  3: '包装车间',
  4: '其他'
};

// 获取车间类型标签
const getWorkshopTypeLabel = (type: number): string => {
  return workshopTypeOptions[type] || '未知';
};

// 表单验证规则
const formRules = reactive({
  workshop_code: [
    { required: true, message: '请输入车间编码', trigger: 'blur' },
    { min: 2, max: 20, message: '车间编码长度应在 2-20 个字符之间', trigger: 'blur' }
  ],
  workshop_name: [
    { required: true, message: '请输入车间名称', trigger: 'blur' },
    { min: 2, max: 50, message: '车间名称长度应在 2-50 个字符之间', trigger: 'blur' }
  ],
  warehouse_id: [
    { required: true, message: '请选择所属仓库', trigger: 'change' }
  ],
  workshop_type: [
    { required: true, message: '请选择车间类型', trigger: 'change' }
  ],
  manager_name: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '负责人姓名长度应在 2-20 个字符之间', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入车间地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度应在 5-200 个字符之间', trigger: 'blur' }
  ]
});

// 搜索表单
const searchForm = reactive<WorkshopQueryParams>({
  workshop_code: undefined,
  workshop_name: undefined,
  workshop_type: undefined,
  is_active: undefined,
  warehouse_id: undefined
});

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = computed(() => isEdit.value ? '编辑车间' : '新增车间');

// 表单数据
const workshopForm = reactive({
  workshop_id: 0,
  workshop_code: '',
  workshop_name: '',
  warehouse_id: undefined,
  workshop_type: undefined,
  production_capacity: undefined,
  manager_name: '',
  phone_number: '',
  address: '',
  description: ''
});

// 表单引用
const workshopFormRef = ref();

// Store实例
const workshopStore = useBaseWorkShopStore();

// 初始化加载数据
onMounted(() => {
  loadWorkshops();
});

// 加载车间列表
const loadWorkshops = async () => {
  try {
    await workshopStore.getWorkshops({
      ...searchForm,
      page_number: workshopStore.currentPage,
      page_size: workshopStore.pageSize
    });
  } catch (error) {
    ElMessage.error('加载车间列表失败');
  }
};

// 处理搜索
const handleSearch = () => {
  workshopStore.setQueryParams(searchForm);
  loadWorkshops();
};

// 处理重置
const handleReset = () => {
  searchForm.workshop_code = undefined;
  searchForm.workshop_name = undefined;
  searchForm.workshop_type = undefined;
  searchForm.is_active = undefined;
  searchForm.warehouse_id = undefined;
  workshopStore.resetQueryParams();
  loadWorkshops();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  workshopStore.setPagination(1, size);
  loadWorkshops();
};

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  workshopStore.setPagination(current, workshopStore.pageSize);
  loadWorkshops();
};

// 处理新增
const handleAdd = () => {
  isEdit.value = false;
  // 重置表单
  workshopForm.workshop_id = 0;
  workshopForm.workshop_code = '';
  workshopForm.workshop_name = '';
  workshopForm.warehouse_id = undefined;
  workshopForm.workshop_type = undefined;
  workshopForm.production_capacity = undefined;
  workshopForm.manager_name = '';
  workshopForm.phone_number = '';
  workshopForm.address = '';
  workshopForm.description = '';
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row: any) => {
  try {
    const detail = await workshopStore.getWorkshopDetail(row.workshop_id);
    if (detail) {
      isEdit.value = true;
      // 复制数据到表单
      Object.assign(workshopForm, {
        workshop_id: detail.workshop_id,
        workshop_code: detail.workshop_code,
        workshop_name: detail.workshop_name,
        warehouse_id: detail.warehouse_id,
        workshop_type: detail.workshop_type,
        production_capacity: detail.production_capacity,
        manager_name: detail.manager_name,
        phone_number: detail.phone_number,
        address: detail.address,
        description: detail.description
      });
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取车间详情失败');
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除车间「${row.workshop_name}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await workshopStore.deleteWorkshop(row.workshop_id);
      ElMessage.success('删除成功');
      loadWorkshops();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理状态变更
const handleStatusChange = async (row: any) => {
  const params: WorkshopStatusParams = {
    workshop_id: row.workshop_id,
    is_active: row.is_active
  };
  try {
    await workshopStore.toggleWorkshopStatus(params);
    ElMessage.success(`${row.is_active ? '启用' : '禁用'}成功`);
  } catch (error) {
    // 回滚状态
    row.is_active = !row.is_active;
    ElMessage.error(`${row.is_active ? '启用' : '禁用'}失败`);
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!workshopFormRef.value) return;

  try {
    await workshopFormRef.value.validate();

    if (isEdit.value) {
      // 编辑模式
      const params: WorkshopUpdateParams = {
        workshop_id: workshopForm.workshop_id,
        workshop_code: workshopForm.workshop_code,
        workshop_name: workshopForm.workshop_name,
        warehouse_id: workshopForm.warehouse_id,
        workshop_type: workshopForm.workshop_type,
        production_capacity: workshopForm.production_capacity,
        manager_name: workshopForm.manager_name,
        phone_number: workshopForm.phone_number,
        address: workshopForm.address,
        description: workshopForm.description
      };
      await workshopStore.updateWorkshop(params);
      ElMessage.success('编辑成功');
    } else {
      // 新增模式
      const params: WorkshopCreateParams = {
        workshop_code: workshopForm.workshop_code,
        workshop_name: workshopForm.workshop_name,
        warehouse_id: workshopForm.warehouse_id || 0,
        workshop_type: workshopForm.workshop_type || 0,
        production_capacity: workshopForm.production_capacity,
        manager_name: workshopForm.manager_name,
        phone_number: workshopForm.phone_number,
        address: workshopForm.address,
        description: workshopForm.description
      };
      await workshopStore.createWorkshop(params);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    loadWorkshops();
  } catch (error) {
    // 表单验证失败或API调用失败
    if (error instanceof Error) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
  if (workshopFormRef.value) {
    workshopFormRef.value.resetFields();
  }
};

// 权限检查（实际项目中应根据用户权限进行判断）
const hasPermission = (permission: string): boolean => {
  // 这里简化处理，假设用户拥有所有权限
  return true;
};
</script>

<style scoped>
.workshop-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  max-height: 500px;
  overflow-y: auto;
}
</style>
